<template>
  <view class="market-container">
    <!-- 顶部统计信息 -->
    <view class="top-header" v-if="totalCount > 0">
      <text class="total-text">全部</text>
      <text class="total-count">{{totalCount }}</text>
    </view>
    
    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 左侧分类栏 -->
      <view class="left-sidebar">
        <scroll-view class="sidebar-scroll" scroll-y="true">
          <view 
            class="category-item" 
            v-for="category in categoriesData?.list" 
            :key="category.id"
            :class="{ active: activeCategory === category.id }"
            @click="selectCategory(category.id)"
          >
            <text class="category-name">{{ category.name }}</text>
          </view>
          
        </scroll-view>
      </view>
      
      <!-- 右侧内容列表 -->
      <view class="right-content">
        <scroll-view 
          class="content-scroll" 
          scroll-y="true"
          @scrolltolower="loadMore"
        >
          <view 
            class="market-item" 
            v-for="item in marketList" 
            :key="item.id"
          >
            <view class="item-left">
              <view class="item-icon">
                <image 
                  :src="item.createdBySumma.avatar" 
                  class="icon-image" 
                  mode="aspectFit"
                  @error="handleImageError"
                ></image>
              </view>
            </view>
            
            <view class="item-center">
              <text class="item-title">{{ item.name || item.title || '未命名应用' }}</text>
              <view class="item-stats">
                <text class="stats-text">
                  {{ item.visitCount || 0 }}人 | 
                  {{ item.interaction_count || item.interactionCount || 0 }}次
                </text>
                <text v-if="item.is_official || item.isOfficial" class="official-tag">官方</text>
              </view>
              <text class="item-desc">{{ item.description || item.desc || '暂无描述' }}</text>
            </view>
            
            <view class="item-right" v-if="!item.isFavorite">
              <view 
                class="add-btn" 
                :class="item.isFavorite?'favorited':''"
                @click="addToFavorites(item)"
              >
                <text class="add-icon">{{ item.isFavorite ? '✓' : '+' }}</text>
              </view>
            </view>
          </view>
          
          <!-- 加载更多提示 -->
          <view class="load-more" v-if="loading">
            <text class="load-text">加载中...</text>
          </view>
          
          <!-- 没有更多数据提示 -->
          <view class="load-more" v-if="!loading && !hasMore && marketList.length > 0">
            <text class="load-text">已加载全部内容</text>
          </view>
          
          <!-- 空状态提示 -->
          <view class="empty-state" v-if="!loading && marketList.length === 0">
            <text class="empty-text">暂无应用数据</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import { userAPI } from '../../utils/api.js'
export default {
  data() {
    return {
      activeCategory: 'all',
      loading: false,
      hasMore: true,
      page: 1,
      pageSize: 20,
      categoriesData: {},
      marketList: [],
      totalCount: 0
    }
  },
  
  onLoad() {
    // 检查登录状态
    this.checkLoginStatus()
    this.getCategoryList()
    this.getAppList()
  },
  
  methods: {
    // 获取分类列表
    async getCategoryList() {
      try {
        const result = await userAPI.categoryList()
        if (result.code === 0) {
          this.categoriesData = result.data
          this.totalCount = result.data?.totalCount
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
        uni.showToast({
          title: '获取分类失败',
          icon: 'none'
        })
      }
    },
    
    // 获取应用列表
    async getAppList(isLoadMore = false) {
      if (this.loading) return
      
      try {
        this.loading = true
        
        const params = {
          page: this.page,
          pageSize: this.pageSize
        }
        
        // 如果不是"全部"分类，则添加分类ID
        if (this.activeCategory !== 'all') {
          params.categoryId = this.activeCategory
        }
        
        const result = await userAPI.appList(params)
        
        if (result.code === 0) {
          const appList = result.data?.list || result.list || []
          
          if (isLoadMore) {
            // 加载更多，追加数据
            this.marketList = [...this.marketList, ...appList]
          } else {
            // 首次加载或切换分类，替换数据
            this.marketList = appList
          }
          
          
          this.hasMore = appList.length === this.pageSize
          
          if (isLoadMore && appList.length === 0) {
            this.hasMore = false
          }
        } else {
          uni.showToast({
            title: result.message || '获取应用列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取应用列表失败:', error)
        uni.showToast({
          title: '获取应用列表失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    // 检查登录状态
    checkLoginStatus() {
      const token = uni.getStorageSync('token')
      if (!token) {
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }
    },
    
    // 选择分类
    selectCategory(categoryId) {
      if (this.activeCategory === categoryId) return
      
      this.activeCategory = categoryId
      this.page = 1 // 重置页码
      this.hasMore = true // 重置加载更多状态
      
      // 根据分类获取应用列表
      this.getAppList()
    },
    
    // 添加到收藏
    async addToFavorites(item) {
      // 如果已经收藏，提示用户
      if (item.isFavorite) {
        uni.showToast({
          title: '已在收藏中',
          icon: 'none'
        })
        return
      }
      
      try {
        // 显示加载提示
        uni.showLoading({
          title: '添加中...'
        })
        
        // 调用添加收藏接口
        const result = await userAPI.addFavorite({
          appId: item.id
        })
        
        uni.hideLoading()
        
        if (result.code === 0 || result.success) {
          // 收藏成功
          uni.showToast({
            title: '已添加到收藏',
            icon: 'success'
          })
          
          // 更新UI状态
          this.updateFavoriteStatus(item.id, true)
        } else {
          // 收藏失败
          uni.showToast({
            title: result.message || '添加收藏失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('添加收藏失败:', error)
        uni.showToast({
          title: error.message || '添加收藏失败',
          icon: 'none'
        })
      }
    },
    
    // 更新收藏状态
    updateFavoriteStatus(appId, isFavorite) {
      // 这里可以更新应用的收藏状态
      // 比如改变按钮样式或更新数据
      const appIndex = this.marketList.findIndex(item => item.id === appId)
      if (appIndex !== -1) {
        // 更新应用的收藏状态
        this.$set(this.marketList[appIndex], 'isFavorite', isFavorite)
      }
    },
    
    // 加载更多
    loadMore() {
      if (this.loading || !this.hasMore) return
      
      this.page += 1
      this.getAppList(true)
    },
    
    // 处理图片加载错误
    handleImageError(e) {
      // 设置默认图片
      const target = e.target
      if (target) {
        target.src = '/static/icons/default-app.png'
      }
    }
  }
}
</script>

<style scoped>
.market-container {
  min-height: calc(100vh - 50px - 42px);
  background-color: #3A3052;
}

.top-header {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: #3A3052;
  position: sticky;
  top: 0;
  font-size: 14px;
  z-index: 100;
}

.total-text {
  color: rgba(255,255,255,0.5);
  font-size: 18px;
  font-weight: 500;
}

.total-count {
  color: #8F82A8;
  font-size: 16px;
  margin-left: 8px;
}

.main-content {
  display: flex;
  height: calc(100vh - 50px - 42px);
}

/* 左侧分类栏 */
.left-sidebar {
  width: 120px;
  background-color: #4A4062;
}

.sidebar-scroll {
  height: 100%;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 15px;
  height: 42px;
  box-sizing: border-box;
  border-bottom: 1px solid rgba(82, 73, 109, 0.3);
  cursor: pointer;
  transition: all 0.3s ease;
}


.category-item.active {
  background-color: #3A3052;
}

.category-name {
  color: rgba(255,255,255,0.5);
  font-size: 16px;
  margin-bottom: 4px;
  text-align: left;
  width: 100%;
}

.category-count {
  color: #8F82A8;
  font-size: 14px;
  background-color: rgba(82, 73, 109, 0.5);
  padding: 2px 6px;
  border-radius: 8px;
  min-width: 20px;
  text-align: center;
}

.search-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 8px;
  border-bottom: 1px solid rgba(82, 73, 109, 0.3);
}

.search-icon {
  font-size: 20px;
  margin-bottom: 8px;
}

.search-text {
  color: #FFFFFF;
  font-size: 16px;
}

.menu-section {
  padding: 16px 8px;
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.menu-item:active {
  background-color: rgba(82, 73, 109, 0.3);
  border-radius: 8px;
}

.menu-text {
  color: #FFFFFF;
  font-size: 16px;
}

.arrow-icon {
  color: #E8B070;
  font-size: 14px;
}

.globe-icon {
  font-size: 18px;
}

/* 右侧内容列表 */
.right-content {
  flex: 1;
  background-color: #3A3052;
}

.content-scroll {
  height: 100%;
  padding: 10px;
}

.market-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #4A4062;
  border-radius: 12px;
  margin-bottom: 10px;
  transition: all 0.3s ease;
}

.market-item:active {
  background-color: #52496D;
  transform: scale(0.98);
}

.item-left {
  margin-right: 10px;
}

.item-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #52496D;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.icon-image {
  width: 40px;
  height: 40px;
}

.item-center {
  flex: 1;
  margin-right: 10px;
  height: 60px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-title {
  color: rgb(254, 213, 189);
  font-size: 18px;
  font-weight: 600;
  display: block;
}

.item-stats {
  display: flex;
  align-items: center;
}

.stats-text {
  color: #8F82A8;
  font-size: 14px;
}

.official-tag {
  color: #E8B070;
  font-size: 14px;
  background-color: rgba(232, 176, 112, 0.2);
  padding: 2px 6px;
  border-radius: 8px;
}

.item-desc {
  color: #8F82A8;
  font-size: 15px;
  line-height: 1.4;
}

.item-right {
  display: flex;
  align-items: center;
}

.add-btn {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: rgb(236, 192, 140);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.add-btn.favorited {
  background-color: #E8B070;
}


.add-icon {
  color: #fff;
  font-size: 22px;
  font-weight: bold;
  padding-bottom: 5px;
}


.load-more {
  text-align: center;
  padding: 20px 0;
}

.load-text {
  color: #8F82A8;
  font-size: 16px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-text {
  color: #8F82A8;
  font-size: 16px;
}
</style>
